import Taro from '@tarojs/taro';
import {Image, View, ScrollView, Text} from '@tarojs/components';
import {AtTabs, AtTabsPane} from 'taro-ui';
import {connect} from "@tarojs/redux";
import {actionCreator} from "../../store/actions";
import './order.scss';
import {request, unite} from "../../utils";
import Head from "../../asset/images/head.png";
import Sao from "../../asset/images/sao.png";
import Xinxin from "../../asset/images/xinxin.png";
import XinxinIn from "../../asset/images/xinxin_in.png";
import none from "../../asset/images/none.png";
import UnionidModal from "../../components/unionid-modal/unionidModal";
import PhoneModal from "../../components/phone-modal/phoneModal";

const appraiseIx = ['1', '2', '3', '4', '5'];

const nameWrap = ['待进行', '预约记录'];

class Order extends Taro.Component{
    config = {
        navigationStyle:'custom',
    };
    state = {
        userData: [], //用户信息
        id: null, //订单id
        appraiseStatus: false, //弹出评价框状态
        orderType: 0, //订单类型 0 待进行、1 已结束
        orderData: [],
        starsIx: 0, //星星评价 最大为5
        unionId: false,
        phoneId: false,
        page: 1,
    };

    temp = {
        isLoading: false,  //防止多次上拉刷新加载
    };

    componentDidShow() {
        const {mobileFlag, existUser} = this.props;
        if (existUser == 0) { //未授权用户信息
            this.setState({
                unionId: true
            });
            return;
        }
        if (mobileFlag == 0) { //未授权手机号
            this.setState({
                phoneId: true
            });
            return;
        }
        this.init(); //获取用户信息
        this.orderList();
    };

    unGetUserInfo = (is) => {
        const {mobileFlag, setExistUser} = this.props;
        if (is) {
            setExistUser(1);
            this.setState({
                phoneId: mobileFlag == 0 ? true : false
            })
        } else {
            Taro.switchTab({
                url: `/pages/index/index`
            })
        }
        this.setState({
            unionId: false, //关闭 nu ni id 弹窗
        });
    };

    //授权手机号
    unGetPhone = (is) => {
        const {setMobileFlag} = this.props;
        if (is) {
            setMobileFlag(1);
            this.init(); //获取用户信息
            this.orderList();
        } else {
            Taro.switchTab({
                url: `/pages/index/index`
            })
        }
        this.setState({
            phoneId: false, //关闭弹窗
        });
    };

    //获取用户信息
    init = () => {
        const params = {
            url: '/wx/firstPage/getUserDetail',
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            userData: res.data,
                        })
                    }
                }
            }
        })
    };

    orderList = () => {
        const {orderType, page} = this.state;
        this.temp.isLoading = true;
        const params = {
            url: '/wx/order/listOrderInfo',
            data:{
                orderType,
                pageNo: page,
                pageSize: 5,
            }
        };
        request(params).then(res => {
            this.temp.isLoading = false; //防止多次上拉加载
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState((prevState)=>({
                            orderData: page == 1 ? res.data : prevState.orderData.concat(res.data),
                        }));
                        //判断是否为最后一页
                        // console.log(res.data.length);
                        if (res.data.length == 0) {
                            this.temp.isLoading = true; //
                        }
                    }
                }
            }
        })
    };

    //切换状态
    typeStatus = (i) => {
        this.setState({
            orderType: i,
            page: 1
        }, () => {
            this.orderList();
        })
    };

    //跳转订单详情页
    skipDetail = (id) => {
        const {orderType} = this.state;

        if (orderType == 0) { //订单类型 0 待进行、1 已结束
            Taro.navigateTo({
                url: './order-detail/orderDetail?id=' + id
            })
        } else {
            Taro.navigateTo({
                url: './order-detail-next/orderDetailNext?id=' + id,
            })
        }
    };

    // //跳转教室详情
    // skipClassRoomDetail = (id, avatar, roomName, address, latitude, longitude, e) => {
    //     e.stopPropagation(); //防止父级点击事件干扰
    //     if (Number(latitude) && Number(longitude)) {
    //         Taro.openLocation({
    //             latitude: Number(latitude),
    //             longitude: Number(longitude),
    //             name: roomName,
    //             address: address
    //         })
    //     } else {
    //         unite.showToast('该店铺暂无经纬度');
    //     }
    // };

    //评价
    appraiseText = (id, e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        this.setState({
            id: id,
            appraiseStatus: true,
        })
    };

    //点击评价
    appraiseType = (is) => {
        this.setState({
            starsIx: Number(is) || 0,
            appraiseStatus: is,
        }, () => {
            if (is) {
                // console.log(is);
                // unite.showToast('评价成功');
                // //    刷新列表
                // this.orderList();
            }
        })
    };

    //评价
    appraiseBtn = () => {
        const {id,} = this.state;
        if (this.state.starsIx == 0) return unite.showToast('请评价');
        const params = {
            url: '/wx/order/remarkOrder',
            data:{
                orderId: id, //订单id
                remarkLevel: this.state.starsIx, // 1到 N 星星
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    this.setState({
                        starsIx: 0,
                        appraiseStatus: false,
                        page: 1
                    })
                    unite.showToast('评价成功');
                    //    刷新列表
                    setTimeout(() => {
                        this.orderList();
                    },1500)
                }
            }
        });
    };

    tabsClick = (is) => {
        this.setState({
            orderType: is,
        }, () => {
            this.orderList();
        })
    };

    //扫码签到
    scanPay = (orderId, e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        let _this = this;
        Taro.scanCode({
            success (res) {
                console.log(res);
            //   res.result.split('=')[1]
                const params = {
                    url: '/wx/firstPage/signDispatch',
                    data:{
                        orderId, //订单id
                        qrcode: res.result, // 扫码数据，目前仅为教室id
                        type: 0,
                    }
                };
                request(params).then(ret => {
                    if (ret) {
                        if(ret.code == 200) {
                            unite.showToast('签到成功');
                            //    刷新列表
                            this.setState({
                                page: 1
                            });
                            setTimeout(() => {
                                _this.orderList();
                            },1500)
                        }
                    }
                });
            }
        })
    };

    //底部上拉刷新加载更多
    onReachBottom() {
        console.log(this.temp.isLoading + 'this.temp.isLoading')
        if(this.temp.isLoading) return;
        this.setState((pervState) =>({
            page: pervState.page + 1
        }),() => {
            this.orderList();
        })
    };

    render() {
        const {orderData, orderType, appraiseStatus, userData, starsIx, unionId, phoneId} = this.state;
        return (
            <View className="page">
                <View className="order-head">
                    <View className="order-head-wrap" style={'padding-top:' + (Taro.getSystemInfoSync()['statusBarHeight']+80) + 'px;'}>
                        <View className="order-head-item">
                            <View className="number">{userData.cumulativeDayCnt}</View>
                            <View className="text flex-center">
                                <View>上课总次数</View>
                                <View className="text-dw">/节</View>
                            </View>
                        </View>
                        <Image className="images" src={userData.avatar || Head} mode="widthFix" />
                        <View className="order-head-item">
                            <View className="number">{userData.cumulativeCnt}</View>
                            <View className="text flex-center">
                                <View>上课总时长</View>
                                <View className="text-dw">/节</View>
                            </View>
                        </View>
                    </View>
                </View>
                <View className="order-list-wrap">
                    <View className="list-top flex-center">
                        {nameWrap.map((item, index) => (
                            <View className={`top-text ${index == orderType ? 'top-text-active' : ''}`} onClick={this.typeStatus.bind(this, index)}>
                                <View className="text">{item}</View>
                                {index == orderType &&(
                                    <View className="text-bottom"></View>
                                )}
                            </View>
                        ))}
                    </View>
                    <AtTabs className="com-tabs" current={orderType} tabList={nameWrap} onClick={this.tabsClick.bind(this)}>
                        {nameWrap.map((va, ixs) => (
                            <AtTabsPane current={orderType} key={ixs} index={ixs+1} >
                                <ScrollView
                                    className="content-view"
                                    scrollY
                                >
                                    <View className="list-bottom">
                                        {orderData && orderData.map((item, index) => (
                                            <View key={index}>
                                                {item.hotClasses && item.hotClasses.map((value, is) => (
                                                    <View className="keep-content-list-item" key={is} onClick={this.skipDetail.bind(this, value.orderId)}>
                                                        <Image className="list-img" src={value.avatar}/>
                                                        <View className="list-centent-left-wrap">
                                                            <View className="list-centent">
                                                                <View className="name">{value.className}</View>
                                                                <View className="timer">{value.classDate + ' '}  {value.classWeekDay + ' '} {value.classBeginTime}-{value.classEndTime}</View>
                                                                {/*<View className="timer">{value.classBeginTime}-{value.classEndTime} <Text className="text">￥{value.price}/节</Text></View>*/}
                                                                <View className="type flex-l">
                                                                    {/*<View className="list-top-left flex-center">{value.reservedInfo}</View>*/}
                                                                    {value.labelNames.map((items, indexs) => (
                                                                        <View className="kepp-gg flex-center" key={indexs}>{items}</View>
                                                                    ))}
                                                                </View>
                                                            </View>
                                                            {(orderType == 0 && value.enableSign == 'Y') &&(
                                                                <View className="btns flex-center" onClick={this.scanPay.bind(this, value.orderId)}>
                                                                    <Image className="sao-img" src={Sao}/>
                                                                    <View>签到</View>
                                                                </View>
                                                            )}
                                                            {(orderType == 0 && value.enableSign == 'N') &&(
                                                                <View style="margin-top: -12rpx;">
                                                                    <View className="btns btns-hui flex-center">
                                                                        <Image className="sao-img" src={Sao}/>
                                                                        <View>签到</View>
                                                                    </View>
                                                                    <View className="hui-text flex-center">开课前30分钟</View>
                                                                </View>
                                                            )}
                                                            {(orderType == 1 && value.refund == 'N' && value.remark == 'N') &&(
                                                                <View className="btns1 flex-center" onClick={this.appraiseText.bind(this, value.orderId)}>评价</View>
                                                            )}
                                                            {(orderType == 1 && value.refund == 'N' && value.remark == 'Y') &&(
                                                                <View className="btns1 btns-next flex-center">已评价</View>
                                                            )}
                                                            {(orderType == 1 && value.refund == 'Y') &&(
                                                                <View className="btns1 btns-next-tk flex-center">已退款</View>
                                                            )}
                                                        </View>
                                                    </View>
                                                ))}
                                            </View>
                                        ))}
                                        {orderData && orderData.length == 0 &&(
                                            <View className="none">
                                                <Image src={none}/>
                                                <View>暂无数据</View>
                                            </View>
                                        )}
                                    </View>
                                </ScrollView>
                            </AtTabsPane>
                        ))}
                    </AtTabs>
                </View>
                {appraiseStatus &&(
                    <View className="appraise-wrap flex-center">
                        <View className="appraise-popup">
                            <View className="appraise-name">课程评价</View>
                            <View className="popup-xinji flex-lr">
                                {appraiseIx.map((item, index) => (
                                    <Image src={Number(starsIx) > Number(index) ? XinxinIn : Xinxin} className="appraise-icon" key={index} onClick={this.appraiseType.bind(this, (index+1))}/>
                                ))}
                            </View>
                            <View className="btns-appraise-wrap flex-lr">
                                <View className="quxiao" onClick={this.appraiseType.bind(this, null)}>取消</View>
                                <View onClick={this.appraiseBtn}>确定</View>
                            </View>
                        </View>
                    </View>
                )}
                {unionId &&(
                    <UnionidModal onCancel={this.unGetUserInfo}/>
                )}
                {phoneId &&(
                    <PhoneModal onCancel={this.unGetPhone}/>
                )}
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {mobileFlag, existUser} = state;
    return {
        mobileFlag,
        existUser
    }
};

const mapDispatchToProps = {
    setExistUser: actionCreator.setExistUser,
    setMobileFlag: actionCreator.setMobileFlag,
};

export default connect(mapStateToProps, mapDispatchToProps)(Order);
